package system

import (
	"cubeAdmin/common"
	"cubeAdmin/common/jwtauth"
	"cubeAdmin/common/utils/gconv"
	"cubeAdmin/controllers"
	"cubeAdmin/models"
	"encoding/json"
	"github.com/beego/beego/v2/core/validation"
)

// DictController 字典api
type DictController struct {
	controllers.BaseController
}

func (c *DictController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
}

// Index 获取菜单列表视图
// @router /index [get]
func (c *DictController) Index() {
	c.Data["pageTitle"] = "字典列表"
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.TplName = "system/dict/main.tpl"
}

// GetAll @Title 获取字典列表
// @Description 获取字典列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *DictController) GetAll() {
	total, list := models.GetAllDict(c.GetParams())
	c.PageTable(gconv.Int64(total), list)
}

// Add 字典添加页面
// @router /add [get]
func (c *DictController) Add() {
	c.Data["title"] = "新增字典"
	c.TplName = "system/dict/add.tpl"
}

// Post @Title 添加字典
// @Description 添加字典
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *DictController) Post() {
	var dictModel models.SysDict
	valid := validation.Validation{}
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &dictModel)
	if err != nil {
		c.Fail(err.Error(), common.UnmarshalErr)
	}
	b, _ := valid.Valid(&dictModel)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, common.ArgsValidErr)
		}
	}
	_, e := models.AddDict(&dictModel)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}

// Edit 跳转到部门编辑
// @router /edit [get]
func (c *DictController) Edit() {
	uid, _ := c.GetInt64("id")
	dept, _ := models.GetDictById(uid)
	c.Data["title"] = "字典修改"
	c.Data["dict"] = dept
	c.TplName = "system/dict/edit.tpl"
}

// Put @Title 修改字典
// @Description 修改字典
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *DictController) Put() {
	var dictModel models.SysDict
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &dictModel)
	b, _ := valid.Valid(&dictModel)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, common.ArgsValidErr)
		}
	}
	e := models.UpdateByDict(&dictModel)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}

// Delete @Title 删除字典
// @Description 删除字典
// @Success 200 {object} controllers.Result
// @router /:id [delete]
func (c *DictController) Delete() {
	id, _ := c.GetInt64(":id", 1)
	e := models.DelByDict(id)
	if e != nil {
		c.Fail(e.Error(), common.DatabaseOperationErr)
	}
	c.Ok("操作成功")
}
